package com.test.googlemaps;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GeoUpdateHandler implements LocationListener {
	Context mContext;
	private List<Overlay> lista;
	private MapController mapController;
	HelloItemizedOverlay itemizedoverlay;
	
	public GeoUpdateHandler(Context mContext,MapController mapController,List<Overlay> lista,HelloItemizedOverlay itemizedoverlay){
		this.lista = lista;
		this.itemizedoverlay = itemizedoverlay;
		this.mapController = mapController;
		this.mContext = mContext;
	}
	
	public void onLocationChanged(Location location) {
		int lat = (int) (location.getLatitude() * 1E6);
		int lng = (int) (location.getLongitude() * 1E6);
		GeoPoint point = new GeoPoint(lat, lng);
		int size = itemizedoverlay.size()-1;
		if (size >= 1) {
			itemizedoverlay.delOverlay(1);
		}
		String add = "";
		try {
			Geocoder geoCoder = new Geocoder(mContext, Locale.getDefault());

            List<Address> addresses = geoCoder.getFromLocation(lat/1E6,lng/1E6,1);
           //public String add = "";
            if (addresses.size() > 0) 
            {
                for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                     i++)
                   add += addresses.get(0).getAddressLine(i) + "\n";
            }

        }
        catch (IOException e) {                
            e.printStackTrace();
            add = "Error";
        }   

		
		OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!",add );
		itemizedoverlay.addOverlay(overlayitem);
		
		
		//lista.remove(size);
		//lista.clear();
		lista.add(itemizedoverlay);
		mapController.animateTo(point); //	mapController.setCenter(point);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		 dialog.setTitle("test");
	}

	
	public void onProviderDisabled(String provider) {
	}

	
	public void onProviderEnabled(String provider) {
	}

	
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}
}
